#include "dbconnection.h"

// Global static pointer used to ensure a single instance of the class.
DBConnection* DBConnection::m_pInstance = NULL;

/* This function is called to create an instance of the class.
   Calling the constructor publicly is not allowed. The constructor
   is private and is only called by this Instance function.
*/
DBConnection* DBConnection::Instance(){
   if (!m_pInstance)   // Only allow one instance of class to be generated.
      m_pInstance = new DBConnection;

   return m_pInstance;
}

bool DBConnection::connect(QString host, QString database, QString user, QString password){

    _db = QSqlDatabase::addDatabase("QMYSQL");
    _db.setHostName(host);
    _db.setDatabaseName(database);
    _db.setUserName(user);
    _db.setPassword(password);

    if(!_db.open()){
        qDebug() << "Error en la apertura de la base de datos.";
        return false;
    }

    _model = new QSqlQueryModel();

    return true;
}

void DBConnection::execQuery(QString query){
    _model->setQuery(query);
}

QSqlQueryModel* DBConnection::getModel(QString query){

    QSqlQueryModel* model = new QSqlQueryModel();
    model->setQuery(query);

    return model;
}

void DBConnection::disconnect(){

    if(_db.open()){
        _db.close();
    }
}
